package hoodoos.flow;


import hoodoos.rule.api.Facts;
import hoodoos.rule.api.GlobalContext;
import hoodoos.rule.api.RequestContext;
import hoodoos.rule.core.DefaultGlobalContext;
import hoodoos.rule.core.DefaultRequestContext;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import lombok.extern.slf4j.Slf4j;

/**
 * 该类需要保证线程安全
 */
@Slf4j
public class StatelessFlowRulesEngine {

  private final ExecutorService executorService;

  public StatelessFlowRulesEngine() {
    this.executorService = Executors.newFixedThreadPool(
        Math.max(Runtime.getRuntime().availableProcessors(), 4));
  }

  public StatelessFlowRulesEngine(ExecutorService executorService) {
    this.executorService = executorService;
  }

  public Facts fire(String flowName, FlowRules flowRules, Map<String, Object> param) {

    // 这个规则的结果，取决于最后一个规则节点的数据
    GlobalContext globalContext = new DefaultGlobalContext();
    RequestContext requestContext = new DefaultRequestContext();
    return doRule(flowName, flowRules.getStartRule(), flowRules, param, globalContext, requestContext);
  }


  private Facts doRule(
      String flowName,
      FlowRule currentNode,
      FlowRules flowRules,
      Map<String, Object> param,
      GlobalContext globalContext,
      RequestContext requestContext) {

    if (currentNode.getType() == FlowRuleTypeEnum.PROCESS_START) {
      // 执行开始节点
    }
    else if (currentNode.getType() == FlowRuleTypeEnum.PROCESS_END) {
      // 执行结束节点
    }
    else if (currentNode.getType() == FlowRuleTypeEnum.PROCESS_BRANCH) {
      // 执行条件分支节点
    }
    else if (currentNode.getType() == FlowRuleTypeEnum.RULE) {
      // 当前节点为规则节点，则需要执行对应的规则
    }
    else if (currentNode.getType() == FlowRuleTypeEnum.PROCESS_PARALLEL) {
      // 并行节点执行
    }
    else if (currentNode.getType() == FlowRuleTypeEnum.PROCESS_MERGE) {
      // 合并节点执行
    }
    throw new RuntimeException("该类型规则未实现");
  }

}
